package com.aos.iot.protocol.hll.encode;

import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.HexUtil;
import com.aos.iot.socket.common.log.service.MessageLogService;
import com.aos.iot.socket.common.protocol.IProtocol;
import com.aos.iot.protocol.hll.message.HllMessage;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.socket.DatagramPacket;
import io.netty.channel.socket.nio.NioDatagramChannel;
import io.netty.handler.codec.MessageToByteEncoder;
import io.netty.handler.codec.MessageToMessageEncoder;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.List;

@Slf4j
public class HllEncoder extends MessageToMessageEncoder<HllMessage> {

    private final IProtocol<HllMessage> protocol;

    private final MessageLogService messageLogService;

    public HllEncoder(IProtocol<HllMessage> protocol, MessageLogService messageLogService) {
        this.protocol = protocol;
        this.messageLogService = messageLogService;
    }

    @Override
    protected void encode(ChannelHandlerContext ctx, HllMessage message, List<Object> out) throws Exception {
        String messageString = protocol.getParser().unboxing(message).toUpperCase();
        byte[] bytes = HexUtil.decodeHex(messageString);
        if(ctx.channel() instanceof NioDatagramChannel) {
            out.add(new DatagramPacket(Unpooled.copiedBuffer(bytes), (InetSocketAddress) message.getSender()));
        } else {
            out.add(bytes);
        }
        ThreadUtil.execute(() -> messageLogService.insertIotLogger(message));
    }
}
